﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Antlr.Runtime;
using System.Windows.Forms;

namespace XYZCompiler
{
    class ParserPart:CompilePartBase
    {
        public override string CompilePartName
        {
            get { return "Parser Part"; }
        }

        public override CompilePartResult Excute(object param)
        {
           
            CompilerHelper.Debug("==========================");
            CompilerHelper.Debug("Start Parser part");
            _hasError = false;
            var tokenStream = param as CommonTokenStream;
            if (tokenStream == null)
            {
                throw  new Exception(StringRes.InputError);
            }
            tokenStream.Reset();
            var parser = new XYZParser(tokenStream);
            parser.Error += ErrorHandler;
            var tree = parser.program();
            parser.Error -= ErrorHandler;
            if(!_hasError)
            {
                CompilerHelper.Debug("Simple statement static:");
                CompilerHelper.Debug("id <= Exp:"+parser.var_assign.ToString());
                CompilerHelper.Debug("id [ Exp ]<= Exp:"+parser.array_member_assign.ToString());
                CompilerHelper.Debug("return Exp:"+parser.return_num.ToString());
                CompilerHelper.Debug("Type id <= Exp:"+parser.var_init.ToString());
                CompilerHelper.Debug("Type id <= [ExpList]:"+parser.array_init.ToString());
            }
            CompilerHelper.Debug("Parser part End");
            CompilerHelper.Debug("==========================");
            if(_hasError)
                return new CompilePartResult(FlowController.CompileState.ERROR, tree.Tree);
            else
                return  new CompilePartResult(FlowController.CompileState.SYNTACTIC_COMPLETED,tree.Tree);
        }
        protected void ErrorHandler(string s,int c ,int r)
        {
            _hasError = true;
            CompilerHelper.Debug(string.Format("{0} in Row:{1} Column:{2}", s, r, c));
            NotifyError(s, c, r);
        }
    }
}
